package com.ziji.springsc.withjpa.model;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@Entity(name = "t_user")    // 指定 Role 是一个实体类，项目启动后，将会根据实体类的属性在数据库中自动创建一个角色表
public class User implements UserDetails {  // 需要实现 UserDetails 以支持 Spring Security
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private boolean accountNonExpired;      // 账户是否没有过期
    private boolean accountNonLocked;       // 账户是否没有被锁定
    private boolean credentialsNonExpired;  // 密码是否没有过期
    private boolean enabled;                // 账户是否可用
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
    private List<Role> roles;               // 用户的角色，User 和 Role 是多对多关系

    // 用户的角色信息
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }
}
